﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Web;
using MyLib;

namespace Billing2.cls
{
    public partial class ClsImportSubscriber
    {
        void PreviewOrganization(Subscriber sub, DBCommands2 db, bool do_not_check_duplicate_in_DB)
        {            
            bool foundOrg = false;
            for (int i = 0; i < this.organizations.Count; i++)
                if (sub.OrgID.IsSameText(this.organizations[i].org))
                {
                    foundOrg = true;
                    break;
                }
            if (!foundOrg && !do_not_check_duplicate_in_DB)
            {
                int n = db.SelectCount("select * from Organization where OrgIDName = @OrgID", sub.OrgID);
                if (n > 0)
                    foundOrg = true;
            }
            if (!foundOrg)
                this.organizations.Add(new Organization(sub.OrgID, sub.OrgFullname, "", ""));

            bool foundSite = false;
            for (int i = 0; i < organizations.Count; i++)
                if (sub.SiteID.IsSameText(organizations[i].site))
                {
                    foundSite = true;
                    break;
                }
            if (!foundSite && !do_not_check_duplicate_in_DB)
            {
                int n = db.SelectCount(@"
                select * from SitesInOrganization
                    inner join Organization on SitesInOrganization.OrgID = Organization.ID
                where SiteIDName=@SiteID and Organization.OrgIDName = @OrgID", sub.SiteID, sub.OrgID);
                if (n > 0)
                    foundSite = true;
            }
            if (!foundSite)
                this.organizations.Add(new Organization(sub.OrgID, sub.OrgFullname, sub.SiteID, ""));

            bool foundCC = false;
            for (int i = 0; i < organizations.Count; i++)
                if (sub.Costcentre.IsSameText(organizations[i].costcentre))
                {
                    foundCC = true;
                    break;
                }
            if (!foundCC && !do_not_check_duplicate_in_DB)
            {
                int n = db.SelectCount(@"
                select * from CostCentresInSite
                    inner join SitesInOrganization on CostCentresInSite.SiteID = SitesInOrganization.ID
                where CostCentreIDName=@Costcentre and SitesInOrganization.SiteIDName=@SiteID", sub.Costcentre, sub.SiteID);
                if (n > 0)
                    foundCC = true;
            }
            if (!foundCC)
                this.organizations.Add(new Organization(sub.OrgID, sub.OrgFullname, sub.SiteID, sub.Costcentre));

            if (!foundOrg && !autoCreateOrgSiteCC)
                throw new Exception(String.Format("Host name '{0}' - New Org/Site/CC found!", sub.AssetID));
            if (!foundSite && !autoCreateOrgSiteCC)
                throw new Exception(String.Format("Host name '{0}' - New Org/Site/CC found!", sub.AssetID));
            if (!foundCC && !autoCreateOrgSiteCC)
                throw new Exception(String.Format("Host name '{0}' - New Org/Site/CC found!", sub.AssetID));
        }

        DBCommands2.TBL_Subscriber FindSubscriber(string AssetID, string Costcentre, string SiteID)
        {
            DBCommands2.TBL_Subscriber old_subsrciber = null;
            if (AssetID == "") throw new Exception("Host name is mandatory");

            old_subsrciber = Common.db.Subscriber.select2("where AssetID = @AssetID order by EffectiveDate desc", AssetID);
            if (old_subsrciber == null)
                throw new Exception(String.Format("Host name '{0}' - Cannot be found.", AssetID));
            return old_subsrciber;
        }

        void PreviewSubscriber(Subscriber sub, DateTime default_start_date, DBCommands2 db, bool do_not_check_subscriber_in_DB)
        {
            DBCommands2.TBL_Subscriber old_subsrciber = null;
            long? new_costcentre_id = 0;

            //for (int i = 0; i < subscribers.Count; i++)
            //    if (sub.AssetID.IsSameText(subscribers[i].AssetID))
            if (subscribers.Contains(sub.AssetID.ToUpper()))
                throw new Exception(String.Format("Host name '{0}' - Exists in this file", sub.AssetID));

            switch (this.ChangeRequestType)
            {
                case ClsChangeRequestHelper.ChangeRequestType.Create:
                    if (sub.AssetID == "")
                        throw new Exception("Host name is mandatory");
                    if (sub.OrgID == "") throw new Exception(String.Format("Host name '{0}' - Organization is mandatory", sub.AssetID));
                    if (sub.OrgFullname == "") throw new Exception(String.Format("Host name '{0}' - Organization Name is mandatory", sub.AssetID));
                    if (sub.SiteID == "") throw new Exception(String.Format("Host name '{0}' - Site is mandatory", sub.AssetID));
                    if (sub.Costcentre == "") throw new Exception(String.Format("Host name '{0}' - Cost Centre is mandatory", sub.AssetID));
                    if (sub.User_Name == "") throw new Exception(String.Format("Host name '{0}' - User Name is mandatory", sub.AssetID));
                    if (sub.Service_Type == "") throw new Exception(String.Format("Host name '{0}' - Service Type is mandatory", sub.AssetID));
                    //Monthly_OneTime;
                    if (sub.Subscription_Start_Date == "")
                    {
                        if (default_start_date == DateTime.MinValue)
                            throw new Exception(String.Format("Host name '{0}' - Subscription Start Date is mandatory", sub.AssetID));
                        else
                            sub.Subscription_Start_Date = default_start_date.ToString("dd-MM-yyyy");
                    }
                    if (!sub.Subscription_Start_Date.IsDateTime())
                        throw new Exception(String.Format("Host name '{0}' - Invalid Subscription Start Date", sub.AssetID));
                    //public string Subscription_End_Date;
                    //public string New_Existing_Terminated;
                    //if (sub.Hostname == "") sub.Hostname = "none"; //throw new Exception("Hostname is mandatory");

                    if (!do_not_check_subscriber_in_DB)
                    {
                        DateTime startDate = sub.Subscription_Start_Date.ToDateTime_dd_MM_yyyy();
                        DateTime endDate;
                        if (sub.Subscription_End_Date == "")
                            endDate = DateTime.MinValue;
                        else
                            endDate = sub.Subscription_End_Date.ToDateTime_dd_MM_yyyy();

                        string rtn = db.SP_Subscriber_CheckStartDate(sub.AssetID, startDate, endDate, 0);
                        if (rtn != "")
                            throw new Exception(String.Format("Host name '{0}' - Create error. {1}", sub.AssetID, rtn));
                    }
                    break;
                case ClsChangeRequestHelper.ChangeRequestType.Teminate:
                    old_subsrciber = FindSubscriber(sub.AssetID, sub.Costcentre, sub.SiteID);

                    if (sub.AssetID == "")
                        throw new Exception("'Host name' is mandatory");
                    if (old_subsrciber.TerminatedDate != DateTime.MinValue)
                        throw new Exception(String.Format("Host name '{0}'​ - Already terminated! Termination Date - {1:dd-MM-yyyy}", old_subsrciber.AssetID, old_subsrciber.TerminatedDate));
                    if ((sub.Service_Type != "") && (sub.Service_Type != old_subsrciber.ServiceType)) throw new Exception(String.Format("Host name '{0}' - Cannot change 'Service Type'", sub.AssetID));
                    if (sub.Subscription_End_Date == "") throw new Exception(String.Format("Host name '{0}' - 'Subscription End Date' is mandatory in Termination Request", sub.AssetID));
                    if (!sub.Subscription_End_Date.IsDateTime()) throw new Exception(String.Format("Host name '{0}' - Invalid 'Subscription End Date'", sub.AssetID));

                    new_costcentre_id = Common.db.SelectLong(@"
                        select CostCentresInSite.ID from CostCentresInSite
                            inner join SitesInOrganization on CostCentresInSite.SiteID = SitesInOrganization.ID
                        where CostCentreIDName=@Costcentre and SitesInOrganization.SiteIDName=@SiteID", sub.Costcentre, sub.SiteID);
                    if (new_costcentre_id == 0)
                        throw new Exception(String.Format("Host name '{0}' - Can not find Costcentre({1})!", sub.AssetID, sub.Costcentre));
                    if (old_subsrciber.CostCentreID != new_costcentre_id)
                        throw new Exception(String.Format("Host name '{0}' - Can not change Org/Site/CC({1}) in Update/Terminate Request!", sub.AssetID, sub.Costcentre));

                    if (sub.Subscription_End_Date.ToDateTime_dd_MM_yyyy() <= old_subsrciber.EffectiveDate)
                        throw new Exception(String.Format("Host name '{0}' - Terminate can not earlier than effective date", sub.AssetID));

                    if (!do_not_check_subscriber_in_DB)
                    {
                        string rtn = db.SP_Subscriber_CheckStartDate(sub.AssetID, old_subsrciber.EffectiveDate, sub.Subscription_End_Date.ToDateTime_dd_MM_yyyy(), old_subsrciber.ID);
                        if (rtn != "")
                            throw new Exception(String.Format("Host name '{0}' - Create error. {1}", sub.AssetID, rtn));
                    }
                    break;
                case ClsChangeRequestHelper.ChangeRequestType.Update:
                    old_subsrciber = FindSubscriber(sub.AssetID, sub.Costcentre, sub.SiteID);

                    if (sub.AssetID == "") throw new Exception("Host name is mandatory");
                    if (sub.AssetID != old_subsrciber.AssetID)
                    {
                        if (LoginUser.GroupName.ToUpper() != "PORTAL ADMIN")
                            throw new Exception(String.Format("Host name '{0}' - Only 'Protal Admin' group can edit Host name", sub.AssetID));
                    }
                    if (sub.Service_Type == "") sub.Service_Type = old_subsrciber.ServiceType;
                    if (sub.Service_Type != "" && sub.Service_Type != old_subsrciber.ServiceType)
                        throw new Exception(String.Format("Host name '{0}' - Cannot change Service Type", sub.AssetID));
                    if (sub.User_Name == "") sub.User_Name = old_subsrciber.Username;
                    //if (sub.Hostname == "") sub.Hostname = "none"; //throw new Exception("Hostname is mandatory");
                    if (sub.New_Existing_Terminated == "") sub.New_Existing_Terminated = (old_subsrciber.Status == 1 ? "Active" : "Inactive");
                    if (sub.Subscription_Start_Date == "") sub.Subscription_Start_Date = old_subsrciber.EffectiveDate.ToString("dd-MM-yyyy");
                    if (sub.Subscription_End_Date == "")
                    {
                        //if (old_subsrciber.TerminatedDate != DateTime.MinValue)
                        //    throw new Exception("Can not change Terminate Date in Update Request");
                        if (old_subsrciber.TerminatedDate != DateTime.MinValue)
                            sub.Subscription_End_Date = old_subsrciber.TerminatedDate.ToString("dd-MM-yyyy");
                    }
                    else
                    {
                        if (!sub.Subscription_End_Date.IsDateTime())
                            throw new Exception(String.Format("Host name '{0}' - Invalid 'Subscription End Date'", sub.AssetID));
                        //if (sub.Subscription_End_Date.ToDateTime_dd_MM_yyyy() != old_subsrciber.TerminatedDate)
                        //    throw new Exception("Can not change Terminate Date in Update Request");
                    }

                    new_costcentre_id = Common.db.SelectLong(@"
                        select CostCentresInSite.ID from CostCentresInSite
                            inner join SitesInOrganization on CostCentresInSite.SiteID = SitesInOrganization.ID
                        where CostCentreIDName=@Costcentre and SitesInOrganization.SiteIDName=@SiteID", sub.Costcentre, sub.SiteID);
                    if (new_costcentre_id == 0)
                        throw new Exception(String.Format("Host name '{0}' - Can not find Costcentre({1})!", sub.AssetID, sub.Costcentre));
                    if (old_subsrciber.CostCentreID != new_costcentre_id)
                        throw new Exception(String.Format("Host name '{0}' - Can not change Org/Site/CC({1}) in Update/Terminate Request!", sub.AssetID, sub.Costcentre));

                    if (sub.Subscription_End_Date != "")
                    {
                        if (sub.Subscription_End_Date.ToDateTime_dd_MM_yyyy() <= old_subsrciber.EffectiveDate)
                            throw new Exception(String.Format("Host name '{0}' - Terminate can not earlier than effective date", sub.AssetID));
                    }

                    if (!do_not_check_subscriber_in_DB)
                    {
                        DateTime startDate = sub.Subscription_Start_Date.ToDateTime_dd_MM_yyyy();
                        DateTime endDate;
                        if (sub.Subscription_End_Date == "")
                            endDate = DateTime.MinValue;
                        else
                            endDate = sub.Subscription_End_Date.ToDateTime_dd_MM_yyyy();

                        string rtn = db.SP_Subscriber_CheckStartDate(sub.AssetID, startDate, endDate, old_subsrciber.ID);
                        if (rtn != "")
                            throw new Exception(String.Format("Host name '{0}' - Create error. {1}", sub.AssetID, rtn));
                    }
                    break;
                case ClsChangeRequestHelper.ChangeRequestType.CostCentreTransfer:
                    if (sub.AssetID == "") throw new Exception("'Host name' is mandatory");
                    if (sub.OrgID == "") throw new Exception(String.Format("Host name '{0}' - 'Organization' is mandatory", sub.AssetID));
                    if (sub.OrgFullname == "") throw new Exception(String.Format("Host name '{0}' - 'Organization Name' is mandatory", sub.AssetID));
                    if (sub.SiteID == "") throw new Exception(String.Format("Host name '{0}' - 'Site' is mandatory", sub.AssetID));
                    if (sub.Costcentre == "") throw new Exception(String.Format("Host name '{0}' - 'Cost Centre' is mandatory", sub.AssetID));
                    if (sub.Subscription_Start_Date == "")
                        throw new Exception(String.Format("Host name '{0}' - 'Subscription Start Date' is mandatory in CostCentreTransfer Request", sub.AssetID));
                    if (!sub.Subscription_Start_Date.IsDateTime()) throw new Exception(String.Format("Host name '{0}' - Invalid 'Subscription Start Date'", sub.AssetID));

                    DataTable dt = db.Select("select * from Subscriber where AssetID = @AssetID order by EffectiveDate desc", sub.AssetID);
                    if (dt.Rows.Count <= 0)
                        throw new Exception(String.Format("Host name '{0}' - Host name does not exists in database", sub.AssetID));
                    long old_cc = (long)dt.Rows[0]["CostCentreID"];
                    dt = db.CostCentresInSite.select("where ID = @ID", old_cc);
                    long old_cc_site = (long)dt.Rows[0]["SiteID"];

                    dt = db.CostCentresInSite.select("where CostCentreIDName = @CostCentreIDName", sub.Costcentre);
                    long new_cc = (long)dt.Rows[0]["ID"];
                    long new_cc_site = (long)dt.Rows[0]["SiteID"];

                    if (old_cc == new_cc)
                        throw new Exception(String.Format("Host name '{0}' - cost centre does not changed in CCT", sub.AssetID));
                    if (old_cc_site != new_cc_site)
                        throw new Exception(String.Format("Host name '{0}' - Can not change site in CCT", sub.AssetID));
                    break;
                default:
                    throw new Exception(String.Format("Host name '{0}' - Do not support batch {1}!", sub.AssetID, this.ChangeRequestType.ToString()));
            }
            subscribers.Add(sub.AssetID.ToUpper(), sub);
        }
    }
}